/* 
 * Copyright (C) 2012 UTSChedule
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package utsc.apps.utschedule.ui.activities.adapters;

import java.util.ArrayList;
import java.util.List;

import utsc.apps.utschedule.classes.Course;
import android.content.Context;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

/**
 * This is used for course spinner dropdown.
 *
 */
public class CourseSpinnerAdapter extends ArrayAdapter<Course> {

	private ArrayList<Course> _courseList;
	private SparseIntArray _courseMap;
	private int _textViewResourceId;
	
	public CourseSpinnerAdapter(Context context, int textViewResourceId,
			List<Course> objects) {
		super(context, textViewResourceId, objects);
		_courseList=new ArrayList<Course>(objects);
		_courseMap=new SparseIntArray(_courseList.size());
		_textViewResourceId=textViewResourceId;
		int count=0;
		for (Course course : objects) {
			_courseMap.put(course.get_courseID(), count);
			count++;
		}
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		
		CourseSpinnerViewHolder holder;
		if (convertView==null) {
			holder=new CourseSpinnerViewHolder();
			convertView=LayoutInflater.from(getContext()).inflate(_textViewResourceId, null);
			holder._txtCourse=(TextView) convertView.findViewById(android.R.id.text1);
			convertView.setTag(holder);
		}else {
			holder=(CourseSpinnerViewHolder) convertView.getTag();
		}
		final Course course=getItem(position);
		holder._txtCourse.setText(course.toString());
		
		return convertView;
	}
	
	@Override
	public Course getItem(int position) {
		if (_courseList!=null) {
			return _courseList.get(position);
		}
		return null;
	}
	
	private static class CourseSpinnerViewHolder{
		TextView _txtCourse;
	}
	
	public void set_courseList(ArrayList<Course> _courseList) {
		this._courseList = _courseList;
		int count=0;
		for (Course course : _courseList) {
			_courseMap.put(course.get_courseID(), count);
			count++;
		}
	}
	
	public int getCoursePosition(int courseID){
		if (_courseMap!=null && _courseMap.size()>0) {
			return _courseMap.get(courseID);
		}
		return 0;
	}

}
